package com.leectrl.server;

import android.util.Log;

import com.leectrl.adapter.AndroidSocketServerHandler;
import com.leectrl.utils.StorageManager;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AndroidSocketServer {
    private ExecutorService mExecutorService = null;// 线程池
    private ServerSocket server = null;
    private AndroidSocketServerHandler androidSocketServerHandler;


    public void run() {
        try {
            server = new ServerSocket(6789);
            mExecutorService = Executors.newCachedThreadPool();// 创建一个线程池
            while (true) {
                //有新的连接
                Log.e("TCP","socket listening");
                Socket socket = server.accept();

                String gatewayWhiteIP = StorageManager.getInstance().getItem("gatewayIp");
                String clientAddress = socket.getInetAddress().getHostAddress();
                if (gatewayWhiteIP != null && gatewayWhiteIP.equals(clientAddress)) {
//                    socket.setKeepAlive(true);
//                    socket.setReuseAddress(true);
//                    socket.setTcpNoDelay(true);
                    androidSocketServerHandler=new AndroidSocketServerHandler(socket);
                    mExecutorService.execute(androidSocketServerHandler);// 开启一个客户端线程.
                } else {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
